package com.qf.confirm;

import com.qf.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author 郗昊天
 * @version 1.0
 * @package com.qf.simple
 * @date 2022/10/14 20:34
 */
public class SenderAsyncReturn {

    private static final String EXCHANGENAME="xhtTopicChange";
    public static void main(String[] args) throws Exception {
        //获取连接
        Connection connection = ConnectionUtils.getconnection();
        //创建通道
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGENAME, "topic");
        //开启发布确认
        channel.confirmSelect();
        //异步接收发布接收结果
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long l, boolean b) throws IOException {
                System.out.println("send successful");
            }

            @Override
            public void handleNack(long l, boolean b) throws IOException {
                System.out.println("send false");
            }
        });

        //添加回退  当消息没有队列接收时自动退回消息
        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int i, String s, String s1, String s2, AMQP.BasicProperties basicProperties, byte[] bytes) throws IOException {
                //当有消息被退回来的时候执行此方法
                System.out.println("消息被退回"+new String(bytes));
            }
        });
        //发送消息
        String msg="贺小倩喊你回家吃饭";

        for (int i = 0; i < 50; i++) {
            //加参数3  true  开启退回机制  不然addreturnListener不生效
            channel.basicPublish(EXCHANGENAME, "user.news",true, null, (msg+i).getBytes());
        }



       // channel.close();
      //  connection.close();
    }
}
